<?php
/**
 * Name: AdminAuthLogic.class.php
 * Description:
 * User: DIY
 * Date: 2016/9/6
 * Time: 18:33
 */

namespace Common\Logic;

use Common\Model\AdminAuthModel;
use Common\Model\AdminRoleModel;

class AdminAuthLogic{
    private $AdminAuthModel;

    public function __construct(){

        $this->AdminAuthModel = new AdminAuthModel();
    }

    /*
     * 获取用户树形菜单
     * */
    public function getAuthTreeByAdmin($admin_id){

        $menu = $this->getAdminAuthListByAdmin($admin_id);

        return $this->createTree($menu);
    }

    /*
     * 获取用户权限节点
     * */
    public function getAdminAuthListByAdmin($admin_id){
        //取得用户角色
        $AdminRole = new AdminRoleModel();
        $role = $AdminRole
            ->alias('p1')
            ->field('p1.*')
            ->join('LEFT JOIN __ADMIN_USER__ AS p2 ON p2.role_id=p1.id')
            ->where(array('p2.id'=>$admin_id))
            ->find();
        $param = array(
            'hide'=>0,
            'id'=>array('in',$role['rules']),
        );
        $menu = $this->AdminAuthModel
            ->where($param)
            ->order('sort desc')
            ->select();
        return $menu;
    }



    /*
     * 获取所有权限节点
     * */
    public function getAdminAuthList(){
        $menu = $this->AdminAuthModel->where(array('hide'=>0))->select();
        return $this->createTree($menu);
    }

    /*
     * 递归生成树形菜单
     * */
    private function createTree($data,$pid=0){
        $tree = array();
        foreach($data as $k => $v){
            if($v['pid']==$pid){
                unset($data[$k]);
                $child = $this->createTree($data,$v['id']);
                if($child){
                    $v['child'] = $child;
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }

}